var EventBase = {};

EventBase.createEventBasicForm = function(){
	var filterPanel = Ext.create('Ext.panel.Panel', {
		bodyPadding: 5,  // Don't want content to crunch against the borders
		defaults:{
	       padding: '2 2 2 0'
	    },
		title: '事件详情',
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',border:true,
		layout: 'column',
		flex: 50/100,
		items: [{
			xtype: 'textfield',
			fieldLabel: '事件名称',
			columnWidth: 0.9,
			id: 'eventname',
			allowBlank: false,
			blankText: '事件名称不能为空'
		}, 
		{
			xtype: 'checkbox',
			fieldLabel: '到期后删除',
			checked: true,
			id: 'dropAfterExpire',
			columnWidth: 1
		},
		{
            xtype      : 'fieldcontainer',
            fieldLabel : '状态',
            defaultType: 'radiofield',
			
			columnWidth: 0.6,
            defaults: {
                flex: 1
            },
            layout: 'hbox',
            items: [
                {
                    boxLabel  : '开启',                    
					checked: true,
					name: 'state',
                    id        : 'stateEnable'
                }, {
                    boxLabel  : '禁用',                    
					name: 'state',
                    id        : 'stateDisable'
                }
            ]
        },
		{
			xtype: 'textarea',
			rows: 3,
			grow: true,
			fieldLabel: "注释",
			columnWidth: 0.9,
			id: 'commentStr'

		}],
		region: 'west',
		renderTo: Ext.getBody()
	});
	
	return filterPanel;
}

EventBase.createEventTiming = function(){

	var setTimingState = function(fixedtiming){
		
		
		Ext.getCmp('fixedtime_dt').setDisabled(!fixedtiming);
		
		
		
		Ext.getCmp('freq_loop_interval_no').setDisabled(fixedtiming);
		Ext.getCmp('freq_loop_interval_unit').setDisabled(fixedtiming);
		Ext.getCmp('freq_loop_startdt_checkbox').setDisabled(fixedtiming);
		
		if( (!fixedtiming) && Ext.getCmp('freq_loop_startdt_checkbox').getValue()){
			Ext.getCmp('freq_loop_startdt').setDisabled(false);
		}
		else{
			Ext.getCmp('freq_loop_startdt').setDisabled(true);
		}
		
		
		Ext.getCmp("freq_loop_enddt_checkbox").setDisabled(fixedtiming);
		if( (!fixedtiming)  && Ext.getCmp("freq_loop_enddt_checkbox").getValue()){
			Ext.getCmp('freq_loop_enddt').setDisabled(false);
		}
		else{
			Ext.getCmp('freq_loop_enddt').setDisabled(true);
		}
		
		
		
	}

	var timingPanel = Ext.create('Ext.panel.Panel', {
		bodyPadding: 5,
		title: '事件时间',
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',border:true,
		region: 'center',
		flex: 50/100,
		layout: 'column',
		defaults:{
			   padding: '2 5'
		},

		items: [
		{
			xtype: 'fieldcontainer',
			columnWidth: 1,
			layout: 'column',
			defaults:{
				   padding: '2 5'
			},

			items:[
                {
					xtype: 'radiofield',
                    boxLabel  : '固定时间',
					columnWidth: 0.2,
                    name      : 'event_freq',
                    inputValue: 'event_freq_fixedtime',
                    id        : 'event_freq_fixedtime',
					listeners:{
						change: function(thiz, newValue, oldValue){
							setTimingState(newValue);
						}
					}

                }, 				
				{
					xtype:'datefield',
					columnWidth: 0.45,
					format: 'Y-m-d H:i:s',
									
					id: 'fixedtime_dt'
				}
			]
		},
		{
			xtype: 'fieldcontainer',
			columnWidth: 1,
			defaults:{
				   padding: '5 5'
			},
			layout: 'column',
			items: [
				{
					xtype: 'radiofield',
                    boxLabel  : '循环时间',
					checked: true,
                    name      : 'event_freq',
                    inputValue: 'event_freq_looptime',
                    id        : 'event_freq_looptime',
					columnWidth: 0.2, 
					listeners:{
						change: function(thiz, newValue, oldValue){
							setTimingState(!newValue);
						}
					}
                },
				{
					xtype:'textfield',			
					fieldLabel: '每',
					
					id: 'freq_loop_interval_no',
					columnWidth: 0.15,					
					labelWidth:20
					
				},
				{
					xtype: 'combo',
					fieldLabel: '',
					
					id: 'freq_loop_interval_unit',
					store: ['YEAR', 'QUARTER', 'MONTH', 'DAY','HOUR','MINUTE', 'WEEK', 'SECOND','YEAR_MONTH','DAY_HOUR','DAY_MINUTE', 'DAY_SECOND','HOUR_MINUTE','HOUR_SECOND', 'MINUTE_SECOND' ],
					columnWidth: 0.3					
				}
			]
		},
		
		{
			xtype: 'fieldcontainer',
			columnWidth: 1,
			defaults:{
				   padding: '5 5'
			},
			layout: 'column',
			items: [
			
			{
				xtype: 'checkbox',
				id: 'freq_loop_startdt_checkbox',
				labelWidth: 70,
				columnWidth: 0.2,
				fieldLabel: '开始时间',
				listeners: {
					change: function(thiz, newValue, oldValue){
						if(newValue){
							Ext.getCmp("freq_loop_startdt").setDisabled(false);
						}
						else{
							Ext.getCmp("freq_loop_startdt").setDisabled(true);
						}
					}
				}
			},
			{
				xtype:'datefield',
				columnWidth: 0.45,
				format: 'Y-m-d H:i:s',
								
				
				id: 'freq_loop_startdt'
			}

			]
		},
		
		{
			xtype: 'fieldcontainer',
			columnWidth: 1,
			defaults:{
				   padding: '5 5'
			},
			layout: 'column',
			items: [
			
			{
				xtype: 'checkbox',
				checked: false,
				
				id: 'freq_loop_enddt_checkbox',
				labelWidth: 70,
				columnWidth: 0.2,
				fieldLabel: '结束时间',
				listeners: {
					change: function(thiz, newValue, oldValue){
						if(newValue){
							Ext.getCmp("freq_loop_enddt").setDisabled(false);
						}
						else{
							Ext.getCmp("freq_loop_enddt").setDisabled(true);
						}
					}
				}
				
			},
			{
				xtype:'datefield',
				columnWidth: 0.45,
						
				format: 'Y-m-d H:i:s',				
				
				id: 'freq_loop_enddt'
			}

			]
		}

		
		],
		renderTo: Ext.getBody()
	});
	
	
	setTimingState(false);
	
	return timingPanel;
}


EventBase.createEventUpperPart = function(){

	var list = [];
	list[0] = EventBase.createEventBasicForm();
	list[1] = EventBase.createEventTiming();
	
	var upperPanel = Ext.create('Ext.panel.Panel',{
		region: 'north',
		//flex: 50/100,
		height:200,
        layout: 'border',
		items:  list
	});
	
	return upperPanel;
}


EventBase.createEventSqlArea = function(){
	 var sqlArea = new Ext.ux.form.field.CodeMirror({id:'eventStatement',autoScroll:true,value:'begin\n\n/**event body**/\n\nend'});
	   var sqlpanel = new Ext.Panel({
	       region:'center', flex: 50/100, title: '事件语句(*)',layout:'fit',items:[sqlArea]
	   		,border:false
	   });
	   
	   return sqlpanel;

}

EventBase.validate = function(){
	var valresult = {};
	
	valresult.success = true;
	
	var errmsg = "";
	if(!Ext.getCmp("eventname").isValid()){
		valresult.success = false;
		errmsg += "<li> 事件名称不能为空 <br/> </li>";
	}
	
	var statement = Ext.getCmp("eventStatement").getValue();
	if((null == statement) || (Ext.isEmpty(Ext.String.trim(statement)))){
		valresult.success = false;
		errmsg += "<li> 事件语句不能为空<br/> </li>";
	}
	
	if(Ext.getCmp("event_freq_fixedtime").checked){
		if(!Ext.getCmp("fixedtime_dt").isValid()){
		
			valresult.success = false;
			errmsg += "<li>固定日期输入不合法</li>";
		}
		
		var fixedtime_dt = Ext.getCmp("fixedtime_dt").getValue();
		if(null == fixedtime_dt){
			valresult.success = false;
			errmsg += "<li>选择了固定日期， 则日期必须输入</li>";
		}
	}
	else if(Ext.getCmp("event_freq_looptime").checked){
		
		var freq_loop_interval_unit = Ext.getCmp("freq_loop_interval_unit").getValue();		
		if((null == freq_loop_interval_unit) || Ext.isEmpty(Ext.String.trim(freq_loop_interval_unit))){
			valresult.success = false;
			errmsg += "<li>循环时间的单位不能为空</li>";
		}
		
		var freq_loop_interval_no = Ext.getCmp("freq_loop_interval_no").getValue();
		
		if( (null == freq_loop_interval_no) ||	Ext.isEmpty(Ext.String.trim(freq_loop_interval_no))){
			valresult.success = false;
			errmsg += "<li>循环时间的次数不能为空</li>";
		}

		if(Ext.getCmp("freq_loop_startdt_checkbox").checked){
			if(!Ext.getCmp("freq_loop_startdt").isValid()){
				valresult.success = false;
				errmsg += "<li>循环时间的起始日期不合法</li>";
			}
		}
		
		if(Ext.getCmp("freq_loop_enddt_checkbox").checked){
			if(!Ext.getCmp("freq_loop_enddt").isValid()){
				valresult.success = false;
				errmsg += "<li>循环时间的结束日期不合法</li>";
			}
		}

	}
	
	
	
	
	valresult.errmsg = errmsg;
	return valresult;
}

EventBase.getCurrentJson = function(){
	var postjson = {};
	postjson["eventname"] = Ext.getCmp("eventname").getValue();
	if(Ext.getCmp("stateEnable").checked){
		postjson["state"] = "ENABLE";
	}
	else if(Ext.getCmp("stateDisable").checked){
		postjson["state"] = "DISABLE";
	}
	else if(Ext.getCmp("stateDisableOnSlave").checked){
		postjson["state"] = "DISABLE ON SLAVE";
	}
	
	postjson["dropafterexpire"] =  Ext.getCmp("dropAfterExpire").checked;
	
	postjson["commentstr"] = Ext.getCmp("commentStr").getValue();
	
	
	if(Ext.getCmp("event_freq_fixedtime").checked){
		postjson["freq"] = "ONE TIME";
		
		postjson["fixedtime_dt"] = Ext.getCmp("fixedtime_dt").getValue();
		
	}
	else{
		postjson["freq"] = "RECURRING";
		
		postjson["freq_loop_interval_unit"] = Ext.getCmp("freq_loop_interval_unit").getValue();
		postjson["freq_loop_interval_no"] = Ext.getCmp("freq_loop_interval_no").getValue();				
		
		if(Ext.getCmp("freq_loop_startdt_checkbox").checked){
			postjson["freq_loop_startdt"] = Ext.getCmp("freq_loop_startdt").getValue();
			
		}
		
		if(Ext.getCmp("freq_loop_enddt_checkbox").checked){
			postjson["freq_loop_enddt"] = Ext.getCmp("freq_loop_enddt").getValue();
			
		}
	}
	
	
	postjson["eventstatement"] = Ext.getCmp("eventStatement").getValue();
	
	postjson["dbname"] = nowDBName;

	return postjson;
}

EventBase.doSave = function(){
	
	var postjson = EventBase.getCurrentJson();
	
	var paramsdata = {"jsondata": Ext.JSON.encode(postjson)};
	
	var saveurl = '/structure/event/saveEvent.do';
	if(operation === "view"){
		saveurl = '/structure/event/modifySaveEvent.do';
		paramsdata["nowDBName"] = postjson["dbname"];
		paramsdata["oldEventName"] = oldEventName;
	}
	
	ajax({
		url: saveurl,
		params: paramsdata,
		method: 'POST',
		success: function(response){

			var resultjson = jsonDecode(response.responseText);

			if(resultjson.success){
				
				$.message.success('保存成功');

				// refresh event
				ajax({
					url: '/structure/event/getEventDetailJson.do',
					params: {'nowDBName': postjson["dbname"], 'objectName': postjson["eventname"]},
					method: 'GET', 
					success: function(response){
						var json = jsonDecode(response.responseText);

						if (json.success) {

							var neventfromdb = json.root;
							window.parent.Ext.getCmp(tabId).setTitle("事件 " + postjson["eventname"]);

							var newtabId = TabUtil.calculateExistingObjPreId(nowDBName, postjson["eventname"], 'event');
							window.parent.console_panel.saveOldNewPanelIdMap(tabId, newtabId);

							window.parent.object_panel.refreshone(window.parent.objectTypeMap.progobjs);

							currEvent = neventfromdb;
							oldEventName = postjson["eventname"];

							fillvalue();

							operation = "view";
						}

					}, 
					failure: function(result){
                        $.message.error('更新内容的时候发生网络异常; 请尝试刷新页面； '  + result);
					}
					
				});
				
				
			}
			else{
				IDBUtil.showErrorMsgBox('Status', '保存失败.', resultjson.errMsgList);				
			}

		},
		failure: function(result){
            $.message.error('网络异常; 请尝试刷新页面； '  + result);
		}

	});


}

EventBase.dopresave = function(){

	var valret =  EventBase.validate();
	if(!valret.success){
		if(valret.errmsg){
			var displaymsg = "<ul>" +  valret.errmsg + "</ul>"
            $.message.error(displaymsg);
		}
		
		return ;
	}

	var postjson = EventBase.getCurrentJson();
	ajax({
		url: '/structure/event/getCreateEventSql.do',
		params: {"jsondata": Ext.JSON.encode(postjson)},
		method: 'POST',
		success: function(response){
			var resultjson = jsonDecode(response.responseText);
			
			if(resultjson.success){
				var confirmButton = new Ext.Button({text:'确定',
					handler:function() {
						EventBase.doSave();

						win.close();
				}});

				var createsql = resultjson.root;
				var allsql = "";
				if(operation === "view"){
					var dropsql = "drop event `"  + postjson["dbname"] + "`.`" + oldEventName + "`;";

					allsql = dropsql + "\n" + createsql;
				}
				else{
					allsql = createsql;
				}

			   var closeButton = new Ext.Button({text:'关闭',handler:function() {win.close();}});
			   var sqlArea = new Ext.ux.form.field.CodeMirror({readOnly:true,value:allsql,autoScroll:true});
			   var win = new IDB.Window({
				   title:('确认执行如下SQL'),width:700,height:450,closable:true,layout:'fit',maximizable:true,
				   items:[sqlArea],buttons:[confirmButton , closeButton]
			   });
			
			} else {
				IDBUtil.showErrorMsgBox('Status', '事件 ' + postjson["eventname"] + ' 添加失败.');
			}

		},
		failure: function(result){
            $.message.error('网络异常; 请尝试刷新页面； '  + result);
		}

	});
	
}

EventBase.createToolBar = function(){

	/*var cancelbtn =  Ext.create('Ext.Button', {
		text: '取消',
		itemId: 'cancelbtn',
		xtype: 'button', 
		handler: function(mbtn){
			
			var theframe = window.parent.Ext.getCmp(tabId);
			theframe.destroy();

			
		}
	});*/

	var savebtn = Ext.create('Ext.Button', {
		text: '保存',
		itemId: 'savebtn',
		xtype: 'button', 
		handler: function(mbtn){
			// EventBase.doSave();
			
			EventBase.dopresave();
		}
	});

	var list = [];
	list.push(savebtn);
	//list.push(cancelbtn);
	
	return list;
}

EventBase.createEventForm = function(){

	var list= [];

	list[0] = EventBase.createEventUpperPart();
	list[1] = EventBase.createEventSqlArea();
	
	
	EventBase.allpanels = Ext.create('Ext.panel.Panel',{
		layout: 'border',
		name: 'eventMainPanel',
		border: false,		
		
		buttons: EventBase.createToolBar(),
		buttonAlign:'center',
		items: list
	});
	
	var formwrapper = Ext.create('Ext.Viewport', {
		 layout:'fit',
		 items: [
		         	EventBase.allpanels
		         ],
		 renderTo: Ext.getBody()
	});
};

function fillvalue(){

			Ext.getCmp("eventname").setValue(currEvent["eventname"]);
			
			if("ENABLE" === currEvent["state"]){
				Ext.getCmp("stateEnable").setValue(true);
			}
			else if("DISABLE" === currEvent["state"]){
				Ext.getCmp("stateDisable").setValue(true);
			}
			else if("DISABLE ON SLAVE" === currEvent["state"]){
				Ext.getCmp("stateDisableOnSlave").setValue(true);
			}
			
			Ext.getCmp("dropAfterExpire").setValue(currEvent["dropafterexpire"]);
			
			Ext.getCmp("commentStr").setValue(currEvent["commentstr"]);
			
			if(currEvent["freq"] === "ONE TIME"){
				Ext.getCmp("event_freq_fixedtime").setValue(true);
				Ext.getCmp("event_freq_looptime").setValue(false);
				
				
				var fixedtime_dt = new Date();
				fixedtime_dt.setTime(currEvent["fixedtime_dt"]);
				Ext.getCmp("fixedtime_dt").setValue(fixedtime_dt);
			}
			else if(currEvent["freq"] === "RECURRING"){
				
				Ext.getCmp("event_freq_fixedtime").setValue(false);
				Ext.getCmp("event_freq_looptime").setValue(true);
				
				Ext.getCmp("freq_loop_interval_unit").setValue(currEvent["freq_loop_interval_unit"]);
				Ext.getCmp("freq_loop_interval_no").setValue(currEvent["freq_loop_interval_no"]);		

				if(currEvent["freq_loop_startdt"]){
					Ext.getCmp("freq_loop_startdt_checkbox").setValue(true);
					Ext.getCmp("freq_loop_startdt").setDisabled(false);
					
					var freq_loop_startdt = new Date();
					freq_loop_startdt.setTime(currEvent["freq_loop_startdt"]);
					
					Ext.getCmp("freq_loop_startdt").setValue(freq_loop_startdt);				
				}
				else{
					Ext.getCmp("freq_loop_startdt_checkbox").setValue(false);
					Ext.getCmp("freq_loop_startdt").setDisabled(true);
				}
				
				if(currEvent["freq_loop_enddt"]){
					Ext.getCmp("freq_loop_enddt_checkbox").setValue(true);
					Ext.getCmp("freq_loop_enddt").setDisabled(false);
					
					var freq_loop_enddt = new Date();
					freq_loop_enddt.setTime(currEvent["freq_loop_enddt"]);
					
					Ext.getCmp("freq_loop_enddt").setValue(freq_loop_enddt);				
				}
				else{
					Ext.getCmp("freq_loop_enddt_checkbox").setValue(false);
					Ext.getCmp("freq_loop_enddt").setDisabled(true);
				}
				
			}
			
			Ext.getCmp("eventStatement").setValue(currEvent["eventstatement"]); 
			nowDBName = currEvent["dbname"];
	
}

Ext.onReady(function(){
	
	EventBase.createEventForm();
	
	if(currEvent){
		fillvalue();
	}
	
});